﻿using System.Globalization;
using TextMateSharp.Themes;
using Spectre.Console;
using Color = Spectre.Console.Color;

namespace Ranger.App;

public static class ConsoleRendering
{
    
    public static void WriteToken(string text, int foreground, int background, int fontStyle, Theme theme)
    {
        if (foreground == -1)
        {
            Console.Write(text);
            return;
        }

        Decoration decoration = GetDecoration(fontStyle);

        Color backgroundColor = GetColor(background, theme);
        Color foregroundColor = GetColor(foreground, theme);

        Style style = new Style(foregroundColor, backgroundColor, decoration);
        Markup markup = new Markup(text.Replace("[", "[[").Replace("]", "]]"), style);

        AnsiConsole.Write(markup);
    }

    static Color GetColor(int colorId, Theme theme)
    {
        if (colorId == -1)
            return Color.Default;

        return HexToColor(theme.GetColor(colorId));
    }

    static Decoration GetDecoration(int fontStyle)
    {
        Decoration result = Decoration.None;

        if (fontStyle == FontStyle.NotSet)
            return result;

        if ((fontStyle & FontStyle.Italic) != 0)
            result |= Decoration.Italic;

        if ((fontStyle & FontStyle.Underline) != 0)
            result |= Decoration.Underline;

        if ((fontStyle & FontStyle.Bold) != 0)
            result |= Decoration.Bold;

        return result;
    }

    static Color HexToColor(string hexString)
    {
        if (hexString.IndexOf('#') != -1)
            hexString = hexString.Replace("#", "");

        byte r, g, b = 0;

        r = byte.Parse(hexString.Substring(0, 2), NumberStyles.AllowHexSpecifier);
        g = byte.Parse(hexString.Substring(2, 2), NumberStyles.AllowHexSpecifier);
        b = byte.Parse(hexString.Substring(4, 2), NumberStyles.AllowHexSpecifier);

        return new Color(r, g, b);
    }
}